//
// Created by Mzoro on 2022/3/7.
//

#include <stdio.h>

/**
 * 练习 3-1
 * 在数组 v 中 找到与 x 相等的数，返回其位置，没有返回-1. n 代表数组的长度，v 是一个按从小到大排序后的数组
 * @param x
 * @param v
 * @param n
 * @return
 */
int binsearch(int x, const int v[], int n);

int main() {
    int v[] = {2, 3,  5, 6, 7, 8, 9, 10, 11};

    int result = binsearch(4, v, 9);
    printf("result %d", result);
    return 0;
}

int binsearch(int x, const int v[], int n) {
    int low = 0;
    int high = n - 1;
    int mid;
    mid = (low + high) / 2;
    while (low < high) {
        if (x < v[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
        mid = (low + high) / 2;
    }

    if (v[mid] == x) {
        return mid;
    } else if (v[mid + 1] == x) {
        return mid + 1;
    } else if (v[mid - 1] == x) {
        return mid - 1;
    } else {
        return -1;
    }
}
